from datetime import timedelta

### Set the time after which the admin session expires
# There are two sessions on pagure, login that holds for 31 days and
# the session defined here after which an user has to re-login.
# This session is used when accessing all administrative parts of pagure
# (ie: changing a project's or a user's settings)
ADMIN_SESSION_LIFETIME = timedelta(minutes=20)

# Make the CSRF token not-time limited, this way it is valid for the entire
# duration of the session.
WTF_CSRF_TIME_LIMIT=None

### Secret key for the Flask application
{% if env == 'pagure-staging' %}
SECRET_KEY='{{ pagure_stg_secret_key }}'
SALT_EMAIL='{{ pagure_stg_secret_salt_email }}'
{% else %}
SECRET_KEY='{{ pagure_secret_key }}'
SALT_EMAIL='{{ pagure_secret_salt_email }}'
{% endif %}

EMAIL_SEND = True

# This is required so that login specifies https
PREFERRED_URL_SCHEME='https'

{% if env == 'pagure-staging' %}
# OpenID server to use
FAS_OPENID_ENDPOINT = 'https://id.stg.fedoraproject.org/openid/'
{% endif %}

### url to the database server:
#DB_URL=mysql://user:pass@host/db_name
#DB_URL=postgres://user:pass@host/db_name
{% if env == 'pagure-staging' %}
DB_URL = 'postgresql://{{ pagure_stg_db_user }}:{{ pagure_stg_db_pass }}@{{ pagure_db_host }}/{{ pagure_stg_db_name }}'
{% else %}
DB_URL = 'postgresql://{{ pagure_db_user }}:{{ pagure_db_pass }}@{{ pagure_db_host }}/{{ pagure_db_name }}'
{% endif %}

### The FAS group in which the admin of pagure are
ADMIN_GROUP = None
PAGURE_ADMIN_USERS = ["pingou", "kevin", "smooge", "mobrien", "nb"]

# The publicly visible admin email address
ADMIN_EMAIL = 'admin@fedoraproject.org'

### The email address to which the flask.log will send the errors (tracebacks)
EMAIL_ERROR = 'pingou@pingoured.fr'

### Default SMTP server to use for sending emails
SMTP_SERVER = 'localhost'

### Email used to sent emails
{% if env == 'pagure-staging' %}
FROM_EMAIL = 'pagure@stg.pagure.io'
DOMAIN_EMAIL_NOTIFICATIONS = 'stg.pagure.io'
{% else %}
FROM_EMAIL = 'pagure@pagure.io'
DOMAIN_EMAIL_NOTIFICATIONS = 'pagure.io'
{% endif %}

### The URL at which the project is available.
{% if env == 'pagure-staging' %}
APP_URL = 'https://stg.pagure.io/'
DOC_APP_URL = 'https://docs.stg.pagure.org'
{% else %}
APP_URL = 'https://pagure.io/'
DOC_APP_URL = 'https://docs.pagure.org'
{% endif %}

### Datagrepper info for the user profile
{% if env == 'pagure-staging' %}
DATAGREPPER_URL = 'https://apps.stg.fedoraproject.org/datagrepper'
{% else %}
DATAGREPPER_URL = 'https://apps.fedoraproject.org/datagrepper'
{% endif %}
DATAGREPPER_CATEGORY = 'pagure'

### The URL to use to clone git repositories.
{% if env == 'pagure-staging' %}
GIT_URL_SSH = 'ssh://git@stg.pagure.io/'
GIT_URL_GIT = 'https://stg.pagure.io/'
{% else %}
GIT_URL_SSH = 'ssh://git@pagure.io/'
GIT_URL_GIT = 'https://pagure.io/'
{% endif %}

### The IP addresses allowed for the internal endpoints
{% if eth0_ipv6_ip is defined %}
IP_ALLOWED_INTERNAL = ['127.0.0.1', 'localhost', '::1', '{{ eth0_ipv4_ip }}' , '{{ eth0_ipv6_ip }}']
{% elif eth0_ipv4_ip is defined %}
IP_ALLOWED_INTERNAL = ['127.0.0.1', 'localhost', '::1', '{{ eth0_ipv4_ip }}']
{% else %}
IP_ALLOWED_INTERNAL = ['127.0.0.1', 'localhost', '::1']
{% endif %}

# Redis configuration
{% if env == 'pagure-staging' %}
EVENTSOURCE_SOURCE = 'https://stg.pagure.io:8088'
{% else %}
EVENTSOURCE_SOURCE = 'https://pagure.io:8088'
{% endif %}
REDIS_HOST = '0.0.0.0'
REDIS_PORT = 6379
REDIS_DB = 0

EV_STATS_PORT = '8888'

WEBHOOK = True

### Folder containing to the git repos
GIT_FOLDER = '/srv/git/repositories'

### Folder containing the forks repos
FORK_FOLDER = '/srv/git/repositories/forks'

### Folder containing the docs repos
DOCS_FOLDER = '/srv/git/repositories/docs'

### Folder containing the pull-requests repos
REQUESTS_FOLDER = '/srv/git/repositories/requests'

### Folder containing the tickets repos
TICKETS_FOLDER = '/srv/git/repositories/tickets'

### Folder containing the clones of the remotes git repo
REMOTE_GIT_FOLDER = '/srv/git/remotes'

### Folder containing out-of-git attachments cache
ATTACHMENTS_FOLDER = '/srv/attachments'

### Configuration file for gitolite
GITOLITE_CONFIG = '/srv/git/.gitolite/conf/gitolite.conf'

### Path of the release folder
{% if env == 'pagure-staging' %}
UPLOAD_FOLDER_URL = 'https://releases.stg.pagure.org/'
{% else %}
UPLOAD_FOLDER_URL = 'https://releases.pagure.org/'
{% endif %}
UPLOAD_FOLDER_PATH = '/var/www/releases/'

### Folder where are cached the archives
ARCHIVE_FOLDER = '/var/www/archives/'


### Home folder of the gitolite user
### Folder where to run gl-compile-conf from
GITOLITE_HOME = '/srv/git/'

### Folder containing all the public ssh keys for gitolite
GITOLITE_KEYDIR = '/srv/git/.gitolite/keydir/'

### Path to the gitolite.rc file
GL_RC = '/srv/git/.gitolite.rc'

### Path to the /bin directory where the gitolite tools can be found
GL_BINDIR = '/usr/bin/'


### Temp folder to be used to make the clones to work around bug in libgit2:
## refs: https://github.com/libgit2/libgit2/issues/2965
## and   https://github.com/libgit2/libgit2/issues/2797
TMP_FOLDER = '/srv/tmp'

# Optional configuration

### Number of items displayed per page
# Used when listing items
ITEM_PER_PAGE = 50

### Maximum size of the uploaded content
# Used to limit the size of file attached to a ticket for example
MAX_CONTENT_LENGTH = 100 * 1024 * 1024  # 100 megabytes

### Lenght for short commits ids or file hex
SHORT_LENGTH = 7

### List of blacklisted project names that can conflicts for pagure's URLs
### or other
BLACKLISTED_PROJECTS = [
    'static', 'pv', 'releases', 'new', 'api', 'settings', 'search', 'fork',
    'logout', 'login', 'user', 'users', 'groups', 'projects', 'ssh_info',
    'issues', 'pull-requests', 'commits', 'tree', 'forks', 'admin', 'c',
    'wait',
]

DISABLED_PLUGINS = ['IRC']


# Authentication related configuration option

### Switch the authentication method
# Specify which authentication method to use, defaults to `fas` can be or
# `local`
# Default: ``fas``.
PAGURE_AUTH = 'openid'

# When this is set to True, the session cookie will only be returned to the
# server via ssl (https). If you connect to the server via plain http, the
# cookie will not be sent. This prevents sniffing of the cookie contents.
# This may be set to False when testing your application but should always
# be set to True in production.
# Default: ``True``.
SESSION_COOKIE_SECURE = True

# The name of the cookie used to store the session id.
# Default: ``.pagure``.
SESSION_COOKIE_NAME = 'pagure'

# Boolean specifying wether to check the user's IP address when retrieving
# its session. This make things more secure (thus is on by default) but
# under certain setup it might not work (for example is there are proxies
# in front of the application).
CHECK_SESSION_IP = True

# Used by SESSION_COOKIE_PATH
APPLICATION_ROOT = '/'

# Set the SSH certs/keys
{% if env == 'pagure-staging' %}
SSH_KEYS = {
    'RSA': {
        'fingerprint': '2048 69:50:46:24:c7:94:44:f8:8d:83:05:5c:eb:73:fb:c4   (RSA)',
        'pubkey': 'stg.pagure.io,8.43.85.77,2620:52:3:1:dead:beef:cafe:fed3 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDJNu490Rp305zGCJLvhVIrKjL7Xngew3NxgRYeopHBDvj+EFQUqULXtgrI5nUBMSB94RrsuHynFAXYy2m0snHjWzWjbIxM4ZVD2sX4GiKX6qu7WyxcGmGcL08MF919r+JSPL9oWWSq/CvvBF0M1eeqkIpjMZHpVKgR3uTMD5yW994NBLAQi9i1UdwGYNQc1KqWvlvW1XhFFtiIGscIFGRKsUOMvnJvWdU6T+djmzMy4hcahxnsPCZxCjbQpuH1JjihNNVWYOq7Ztjs1gxpTTV19ATp4Z2F95uyyQ3Y+Em9KeXcKXYxwVzYVho5SSB1ZYBL+xAH1osK23PvGD39UYp9',
        'SHA256': 'SHA256:x4xld/tPdeOhbyJcTOxd+IbSZ4OpnBzh/IskocyrOM',
    }
}
{% else %}
SSH_KEYS = {
    'RSA': {
        'fingerprint': '2048 90:8e:7f:a3:f7:f1:70:cb:56:77:96:17:44:c4:fc:82   (RSA)',
        'pubkey': 'pagure.io,8.43.85.75,2620:52:3:1:dead:beef:cafe:fed5 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC198DWs0SQ3DX0ptu+8Wq6wnZMrXUCufN+wdSCtlyhHUeQ3q5B4Hgto1n2FMj752vToCfNTn9mWO7l2rNTrKeBsELpubl2jECHu4LqxkRVihu5UEzejfjiWNDN2jdXbYFY27GW9zymD7Gq3u+T/Mkp4lIcQKRoJaLobBmcVxrLPEEJMKI4AJY31jgxMTnxi7KcR+U5udQrZ3dzCn2BqUdiN5dMgckr4yNPjhl3emJeVJ/uhAJrEsgjzqxAb60smMO5/1By+yF85Wih4TnFtF4LwYYuxgqiNv72Xy4D/MGxCqkO/nH5eRNfcJ+AJFE7727F7Tnbo4xmAjilvRria/+l',
        'SHA256': 'SHA256:Gddkd5H7oQ1RaK8WgXSKl7JZP+FgLyidmxbLercJ/JY',
    }
}
{% endif %}

# Allow the backward compatiblity endpoints for the old URLs schema to
# see the commits of a repo. This is only interesting if you pagure instance
# was running since before version 1.3 and if you care about backward
# compatibility in your URLs.
OLD_VIEW_COMMIT_ENABLED = True

PAGURE_CI_SERVICES=['jenkins']

from pagure.mail_logging import ContextInjector, MSG_FORMAT
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
        },
        'email_format': {
            'format': MSG_FORMAT
        }
    },
    'filters': {
        'myfilter': {
            '()': ContextInjector,
        }
    },
    'handlers': {
        'console': {
            'formatter': 'standard',
            'class': 'logging.StreamHandler',
            'stream': 'ext://sys.stderr',
        },
        'email': {
            'level': 'ERROR',
            'formatter': 'email_format',
            'class': 'logging.handlers.SMTPHandler',
            'mailhost': 'localhost',
            'fromaddr': 'pagure@pagure.io',
            'toaddrs': 'pingou@pingoured.fr',
            'subject': 'ERROR on pagure.io',
            'filters': ['myfilter'],
        },
        "auth_handler": {
           "formatter": "standard",
           "class": "logging.handlers.TimedRotatingFileHandler",
           "filename": "/var/log/pagure/pagure_auth.log",
           "backupCount": 10,
           "utc": True,
           "when": "midnight",
       },

    },
    # The root logger configuration; this is a catch-all configuration
    # that applies to all log messages not handled by a different logger
    'root': {
        'level': 'INFO',
        'handlers': ['console', 'email'],
    },
    'loggers': {
        'pagure': {
            'handlers': ['console', 'email'],
            'level': 'DEBUG',
            'propagate': True
        },
        "pagure_auth": {
            "handlers": ["auth_handler"],
            "level": "DEBUG",
            "propagate": False,
        },
        'flask': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False
        },
        'sqlalchemy': {
            'handlers': ['console'],
            'level': 'WARN',
            'propagate': False
        },
        'binaryornot': {
            'handlers': ['console'],
            'level': 'WARN',
            'propagate': True
        },
        'pagure.lib.encoding_utils': {
            'handlers': ['console'],
            'level': 'WARN',
            'propagate': False
        },
        "pagure.pfmarkdown" : {
            'handlers': ['console'],
            'level': 'WARN',
            'propagate': False
        },
    }
}

LOGGING_GIT_HOOKS = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
        },
        'email_format': {
            'format': MSG_FORMAT
        }
    },
    'filters': {
        'myfilter': {
            '()': ContextInjector,
        }
    },
    'handlers': {
        'console': {
            'formatter': 'standard',
            'class': 'logging.StreamHandler',
            'stream': 'ext://sys.stdout',
            'level': 'WARN',
        },
        'email': {
            'level': 'ERROR',
            'formatter': 'email_format',
            'class': 'logging.handlers.SMTPHandler',
            'mailhost': 'localhost',
            'fromaddr': 'pagure@pagure.io',
            'toaddrs': 'pingou@pingoured.fr',
            'subject': 'ERROR on pagure.io',
            'filters': ['myfilter'],
        },
        "auth_handler": {
           "formatter": "standard",
           "class": "logging.handlers.TimedRotatingFileHandler",
           "filename": "/var/log/pagure/pagure_auth.log",
           "backupCount": 10,
           "utc": True,
           "when": "midnight",
       },
    },
    # The root logger configuration; this is a catch-all configuration
    # that applies to all log messages not handled by a different logger
    'root': {
        'level': 'WARN',
        'handlers': ['console', 'email'],
    },
    'loggers': {
        "pagure_auth": {
            "level": "DEBUG",
            "handlers": ["auth_handler"],
            "propagate": False,
        },
    }
}

CROSS_PROJECT_ACLS = [
    'create_project',
    'fork_project',
    'modify_project',
    'issue_create',
    'issue_comment',
    'issue_change_status',
    'issue_update',
    'pull_request_create',
    'pull_request_comment',
    'pull_request_merge',
    'pull_request_flag',
    'pull_request_close',
    'commit',
]

BLACKLISTED_GROUPS = ['forks', 'group', 'rpms', 'modules', 'container', 'tests']

GITOLITE_CELERY_QUEUE = 'gitolite_queue'
FAST_CELERY_QUEUE = 'fast_workers'
MEDIUM_CELERY_QUEUE = 'medium_workers'
SLOW_CELERY_QUEUE = 'slow_workers'
PRIVATE_PROJECTS = False
FEDMSG_NOTIFICATIONS = False
FEDORA_MESSAGING_NOTIFICATIONS = True
THEME = 'pagureio'

MIRROR_SSHKEYS_FOLDER='/srv/mirror/ssh'

SSH_KEYS_USERNAME_EXPECT = "git"
SSH_KEYS_OPTIONS = 'restrict,command="/usr/libexec/pagure/aclchecker.py %(username)s"'

SSH_COMMAND_NON_REPOSPANNER = ([
    "/usr/bin/%(cmd)s",
    "/srv/git/repositories/%(reponame)s",
], {"GL_USER": "%(username)s"})



GIT_AUTH_BACKEND = 'pagure'
HTTP_REPO_ACCESS_GITOLITE = None

{% if env == 'pagure-staging' %}
ALLOW_HTTP_PUSH = True

CSP_HEADERS = (
    "default-src 'self';"
    "script-src 'self' '{nonce_script}'; "
    "style-src 'self' '{nonce_style}'; "
    "object-src 'none';"
    "base-uri 'self';"
    "img-src 'self' https:;"
    "connect-src 'self' https://stg.pagure.io:8088;"
    "frame-src https://docs.stg.pagure.org;"
    "frame-ancestors https://stg.pagure.io;"
)
{% else %}
CSP_HEADERS = (
    "default-src 'self';"
    "script-src 'self' '{nonce_script}'; "
    "style-src 'self' '{nonce_style}'; "
    "object-src 'none';"
    "base-uri 'self';"
    "img-src 'self' https:;"
    "connect-src 'self' https://pagure.io:8088;"
    "frame-src https://docs.pagure.org;"
    "frame-ancestors https://pagure.io;"
)
{% endif %}
